package com.qi.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.qi.common.exception.BizCodeEnume;
import com.qi.common.utils.R;
import com.qi.common.constant.AuthServerConstant;
import com.qi.common.vo.MemberRespVo;
import com.qi.gulimall.auth.feign.MemberFeignService;
import com.qi.gulimall.auth.feign.ThirdPartFeignService;
import com.qi.gulimall.auth.vo.UserLoginVo;
import com.qi.gulimall.auth.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 周玉琦
 * @date 2020/9/16 - 22:48
 */
@Controller
public class LoginController {

    @Resource
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Resource
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone){
        //TODO 接口防刷

        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_PREFIX + phone);
        if(!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if(System.currentTimeMillis()-l<60000){
                //60秒内不能再发
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        //验证码的再次校验,redis sms:code:17630522653 -> 45826
        String code = UUID.randomUUID().toString().substring(0, 5);
        //redis缓存验证码,防止同一个phone在60秒内再次发送验证码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_PREFIX+phone,code+"_"+System.currentTimeMillis(),10, TimeUnit.MINUTES);

        thirdPartFeignService.sendCode(phone,code);
        return R.ok();
    }

    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, Model model, RedirectAttributes redirectAttributes){
        if(result.hasErrors()){
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors",errors);
            //校验出错,转发到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //校验验证码
        String code = vo.getCode();

        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_PREFIX + vo.getPhone());
        if(!StringUtils.isEmpty(s)){
            //截取出真正的验证码
            String redisCode = s.split("_")[0].toString();
            if(vo.getCode().equals(redisCode)){
                //删除redis中的验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_PREFIX + vo.getPhone());

                //验证码正确 调用远程服务进行注册
                R r = memberFeignService.regist(vo);
                if(r.getCode()==0){
                    //注册成功
                    System.out.println("注册成功!跳转到登录页redirect:http://auth.gulimall.com/login.html");
                    return "redirect:http://auth.gulimall.com/login.html";
                }else{
                    //注册失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }

            }else{
                //验证码错误
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                //校验出错,转发到注册页
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else{
            //redis没有验证码
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            //校验出错,转发到注册页
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //注册成功回到首页,或者登录页
//        return "redirect:/login.html";
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object loginUser = session.getAttribute("loginUser");
        if(loginUser==null){
            return "login";
        }else{
            return "redirect:http://gulimall.com";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){
        //调用远程登录服务
        R login = memberFeignService.login(vo);
        if(login.getCode()==0){
            //登录成功
            System.out.println("手机号注册登录成功!跳转到redirect:http://gulimall.com");
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {
            });
            session.setAttribute("loginUser",data);
            return "redirect:http://gulimall.com";
        }else{
            //登录失败,账号或密码错误
            Map<String,String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            System.out.println("登录失败!跳转到redirect:http://auth.gulimall.com/login.html");
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
